package com.mt.api.core.config.mvc;

import com.google.common.collect.Sets;
import com.mt.api.core.config.interceptor.RepeatReqHandlerIntreceptor;
import com.mt.api.core.config.interceptor.TokenHandlerInterceptor;
import com.mt.api.core.config.property.ConfigProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.Set;

/**
 * @Author: plover
 * @Date: 2020/07/08/11:10 上午
 * @Description:
 */
@Configuration
@RequiredArgsConstructor
public class BusinessWebMvcConfiguration extends WebMvcConfigurationSupport {

    private final TokenHandlerInterceptor tokenHandlerInterceptor;
    private final RepeatReqHandlerIntreceptor repeatReqHandlerIntreceptor;
    private final ConfigProperties configProperties;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        Set<String> securityIgnoreUrls = Sets.newHashSet();
        securityIgnoreUrls.addAll(configProperties.getSecurityIgnoreUrls());
        String[] ignores = new String[securityIgnoreUrls.size()];
        registry.addInterceptor(repeatReqHandlerIntreceptor)
                .addPathPatterns("/app/**");
        registry.addInterceptor(tokenHandlerInterceptor)
                .addPathPatterns("/app/**")
                .excludePathPatterns(securityIgnoreUrls.toArray(ignores));
        super.addInterceptors(registry);
    }

    /**
     * 发现如果继承了WebMvcConfigurationSupport，则在yml中配置的相关内容会失效。 需要重新指定静态资源
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedMethods("*")
                .allowedOriginPatterns("*")
                .allowedHeaders("*");
        super.addCorsMappings(registry);
    }
}
